/*
   Copyright (c) 2015 Mizar Tools Contributors (mizartools.org)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
/*  Contributors : 
 *  Marco Riccardi
 *  2015-02-07 - initial implementation
 *
 */
package org.mizartools.example.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.mizartools.dli.utility.DirectoryFactory;
import org.mizartools.dli.utility.Exporter;
import org.mizartools.system.ListArticleFile;
import org.mizartools.utility.UtilityFile;

@SuppressWarnings("serial")
public class UtilityDliCreateDatabasePanel extends JPanel {

	private JTextArea textArea;
	private JScrollPane scroller;
	private JProgressBar progressBar;
	private JButton button;
	private UtilityDliFrame utilityDliFrame;

	public UtilityDliCreateDatabasePanel(UtilityDliFrame utilityDliFrame){
		super();
		this.utilityDliFrame = utilityDliFrame;
    	setLayout(new BorderLayout());
		setPreferredSize(new Dimension(500, 150));
		button = new JButton();
		AbstractAction action =  new AbstractAction() { 
	 	    public void actionPerformed(ActionEvent e) {
	 	    	textArea.setText(Calendar.getInstance().getTime().toString()+"\n\n");
	 			Job job = new Job();
	 			Thread thread = new Thread(job);
	 			thread.start();
	 	    } 
	 	}; 
	 	button.setAction(action);
	 	button.setMaximumSize(getMaximumSize());
	 	button.setText("Start");
		add(button, BorderLayout.NORTH);
		textArea = new JTextArea();
		textArea.setEditable(false);
        scroller = new JScrollPane();
		scroller.getViewport().add(textArea);
		add(scroller, BorderLayout.CENTER);
		progressBar = new JProgressBar();
		add(progressBar, BorderLayout.SOUTH);
		
	}
	
	private class Job implements Runnable {

		@Override
		public void run() {
			button.setEnabled(false);
			LinkedList<String> articleList = ListArticleFile.getAllArticleList();
	    	progressBar.setMaximum(articleList.size()+1);
	    	progressBar.setValue(0);
	    	progressBar.setIndeterminate(false);
	    	String dliString = null;
	    	int progress = 0;
			try {
				String dliPath = DirectoryFactory.getDliArticlesDirectory().getAbsolutePath();
				Exporter exporter = new Exporter();
				boolean error = false;
		    	for (String aid : articleList){
		    		if (progress++ < 0) continue;
		    		if (!error){
						textArea.append((aid+" ["+progress+"]        ").substring(0,15)+" : ");
			    		File dliFile = new File(dliPath, aid.toLowerCase()+".dli");
			    		String text = UtilityFile.readFile(dliFile);
			    		String arrayText[] = text.split("\n");
			    		for (int i = 0; i<arrayText.length; i++){
			    			dliString = arrayText[i];
			    			exporter.put(dliString);
			    			if (i%10 == 0) textArea.append(".");
			    		}
						if (error) {
							textArea.append("[ERROR IMPORT] ["+dliFile.getAbsolutePath().toLowerCase()+"]");
						} else {
							textArea.append("[OK] ["+arrayText.length+"]");
						}
						textArea.append("\n");
			    		textArea.repaint();
			    		textArea.setCaretPosition(textArea.getText().length()-1);
				    	progressBar.setValue(progress);
				    	progressBar.repaint();
				    	if (utilityDliFrame.isClosed()) {
				    		error = true;
				    	}
		    		}
		    	}
				if (!error) {
					File dliDatabasePath = DirectoryFactory.getDliDatabaseDirectory();
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "aggrnot.dli"), exporter.getAggregateNotation().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "attrnot.dli"), exporter.getAttributeNotation().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "forgnot.dli"), exporter.getForgNotation().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "funcnot.dli"), exporter.getFunctorNotation().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "modenot.dli"), exporter.getModeNotation().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "prednot.dli"), exporter.getPredicateNotation().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "selnot.dli"), exporter.getSelectorNotation().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "structnot.dli"), exporter.getStructureNotation().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "aggr.dli"), exporter.getAggregate().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "attr.dli"), exporter.getAttribute().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "dfs.dli"), exporter.getDefiniens().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "func.dli"), exporter.getFunctor().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "mode.dli"), exporter.getMode().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "pred.dli"), exporter.getPredicate().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "sel.dli"), exporter.getSelector().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "struct.dli"), exporter.getStructure().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "sch.dli"), exporter.getScheme().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "th.dli"), exporter.getTheorem().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "def.dli"), exporter.getDefinitionalTheorem().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "condreg.dli"), exporter.getConditionalRegistration().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "exreg.dli"), exporter.getExistentialRegistration().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "idreg.dli"), exporter.getIdentifyRegistration().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "redreg.dli"), exporter.getReductionRegistration().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "funcreg.dli"), exporter.getTermAdjectiveRegistration().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "sethood.dli"), exporter.getSethood().values());
					if (!error) error = !UtilityFile.writeFile(new File(dliDatabasePath, "item"), exporter.getItem());
				}
			} 
			catch (Exception e) {
				textArea.append("\n");
	    		textArea.append(dliString);
	    		textArea.append(" -> Error");
				textArea.append("\n");
	    		textArea.append(e.getMessage());
	    		textArea.append(e.getStackTrace().toString());
				textArea.append("\n");
	    		textArea.repaint();
	    		textArea.setCaretPosition(textArea.getText().length()-1);
			}
			textArea.append("\n");
			textArea.repaint();
			textArea.setCaretPosition(textArea.getText().length()-1);
	    	progressBar.setValue(0);
			button.setEnabled(true);
		}
		
	}

}
